# from gevent import monkey
# monkey.patch_all()
from flask import Flask, request
from flask_socketio import SocketIO
from flask_cors import CORS
from task import run_steps
import threading
import redis
import json
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# 存储前端连接的 socket id 映射（可选）
client_sid_map = {}
# Redis PubSub 用于监听 Celery 发来的数据
def redis_listener():
    r = redis.Redis(host='localhost', port=6379, db=2)
    pubsub = r.pubsub()
    pubsub.subscribe('steps')  # 监听 Celery 发布的“步骤更新”消息
    for message in pubsub.listen():
        if message['type'] == 'message':
            try:
                data = json.loads(message['data'])
                sid = data.get('sid')
                step = data.get('step')
                result = data.get('result')
                print(f"[推送] SID: {sid}, STEP: {step}, RESULT: {result}")
                socketio.emit('step_result', {'step': step, 'result': result}, to=sid)
            except Exception as e:
                print(f"处理 Redis 消息失败: {e}")

# 启动 Redis 监听线程（后台运行）
threading.Thread(target=redis_listener, daemon=True).start()
@app.route('/start', methods=['POST'])
def start_task():
    data = request.json
    topic = data.get('topic')
    level = data.get('level')
    sid = data.get('sid')
    client_sid_map[sid] = True
    task = run_steps.delay(topic, level, sid)
    return {'task_id': task.id}



@socketio.on('connect')
def handle_connect():
    print("客户端连接成功")

if __name__ == '__main__':
    socketio.run(app, debug=True, port=5123)
